import logging

from odoo import fields, models, api, _

_logger = logging.getLogger(__name__)


class StockMove(models.Model):
    _inherit = 'stock.move'

    s_pr_product_qty = fields.Float(string='Requisition Quantity',
                                    compute='_compute_s_pr_product')
    s_pr_product_uom = fields.Many2one('uom.uom',
                                       string='Requisition Uom',
                                       compute='_compute_s_pr_product')
    s_uom_po_id = fields.Many2one('uom.uom', 'Purchase Uom', related='product_id.uom_po_id', store=True)
    s_purchase_qty = fields.Float(string='Purchase Quantity', compute='_compute_s_product_qty', store=True)

    @api.depends('s_uom_po_id', 'product_uom_qty', 'product_uom')
    def _compute_s_product_qty(self):
        for record in self:
            if record.picking_id.state == 'cancel':
                record.s_purchase_qty = 0
                continue
            if not record.s_uom_po_id:
                record.s_purchase_qty = record.product_uom_qty
                continue
            if record.s_uom_po_id != record.product_uom:
                qty = record.product_uom._compute_quantity(record.product_uom_qty, record.s_uom_po_id)
                record.s_purchase_qty = qty
            else:
                record.s_purchase_qty = record.product_uom_qty

    @api.depends('product_id')
    def _compute_s_pr_product(self):
        for record in self:
            if record.picking_id.state == 'cancel':
                record.s_pr_product_qty = 0
                record.s_pr_product_uom = False
                continue
            pr_line_id = record.purchase_line_id.pr_line_id
            if not pr_line_id:
                record.s_pr_product_qty = 0
                record.s_pr_product_uom = False
                continue
            record.s_pr_product_uom = pr_line_id.product_uom_id
            if record.s_pr_product_uom != record.product_uom:
                # 进行单位数量转换
                record.s_pr_product_qty = record.product_uom._compute_quantity(record.product_uom_qty,
                                                                               pr_line_id.product_uom_id)
            else:
                record.s_pr_product_qty = record.product_uom_qty
